package ru.gerunn.silent.server;

import java.io.IOException;
import java.util.HashMap;

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

import ru.gerunn.silent.message.MessageQueue;
import ru.gerunn.silent.message.MessageQueueThread;

public class Server extends Thread {

	private final int port;
	private boolean logToConsole = false;
	private HashMap<String, Session> sessions;
	private MessageQueue messageQueue;

	public Server() {
		this.port = 8883;
	}

	public Server(int port) {
		this.port = port;
	}

	public void run() {
		try {
			SSLServerSocketFactory serverSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
			SSLServerSocket serverSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(this.port);
			SSLSocket socket = null;

			this.setSessions(new HashMap<String, Session>());
			this.setMessageQueue(new MessageQueue());
			MessageQueueThread messageQueueThread = new MessageQueueThread(messageQueue, this);
			messageQueueThread.start();

			while ((socket = (SSLSocket) serverSocket.accept()) != null) {
				this.addSession(socket);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean isLogToConsole() {
		return logToConsole;
	}

	public void setLogToConsole(boolean logToConsole) {
		this.logToConsole = logToConsole;
	}

	public HashMap<String, Session> getSessions() {
		return sessions;
	}

	private void setSessions(HashMap<String, Session> sessions) {
		this.sessions = sessions;
	}

	synchronized private void addSession(SSLSocket socket) throws IOException {
		Session session = new Session(socket, this);
		session.start();
	}

	synchronized public void removeSession(String key) {
		this.sessions.remove(key);
	}

	public MessageQueue getMessageQueue() {
		return messageQueue;
	}

	private void setMessageQueue(MessageQueue messageQueue) {
		this.messageQueue = messageQueue;
	}

}
